// filePath：softclass-platform/public/js/class.js
// 创建班级
export async function createClass() {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const response = await fetch(`/user-info?username=${escapeHTML(username)}`);
    const data = await response.json();
    if (data.role === '教师') {
        const { user_id } = data;
        document.getElementById('createClassModal').style.display = 'block';
        document.getElementById('classCreatorId').value = user_id;
    } else {
        alert('该功能为教师专属，非教师无法使用');
    }
}

// 关闭创建班级模态框
export function closeCreateClassModal() {
    document.getElementById('createClassModal').style.display = 'none';
}

// 保存班级
export async function saveClass() {
    const classCode = document.getElementById('classCode').value.trim();
    const className = document.getElementById('className').value.trim();
    const classCreatorId = document.getElementById('classCreatorId').value;

    if (!classCode || !className) {
        alert('班级信息不合法');
        return;
    }
    if(className.length>25){
        alert('班级名称不能超过25个字符');
        return;
    }
    if(classCode.length>25){
        alert('班级编号不能超过25个字符');
        return;
    }

    // 检查班级编号是否已存在
    const checkResponse = await fetch(`/check-class-code?classCode=${escapeHTML(classCode)}`);
    const checkData = await checkResponse.json();
    if (checkData.exists) {
        alert('班级编号已存在');
        return;
    }

    // 发送创建班级请求
    const response = await fetch('/create-class', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            classCode,
            className,
            classCreatorId
        })
    });
    const result = await response.json();
    alert(result.message);
    closeCreateClassModal();
}

// 加入班级
export async function joinClass() {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    
    try {
        // 获取用户信息
        const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
        const userData = await userResponse.json();
        
        // 检查用户是否为教师
        if (userData.role === '教师') {
            alert('教师无法使用该功能');
            return;
        }
        
        // 检查用户是否已加入班级
        const checkResponse = await fetch(`/check-user-in-class?userId=${escapeHTML(userData.user_id)}`);
        const checkData = await checkResponse.json();
        
        if (checkData.inClass) {
            alert('你已经加入了一个班级');
            return;
        }
        
        // 打开加入班级模态框
        //document.getElementById('joinClassModal').style.display = 'block';
        const modal=document.getElementById('joinClassModal');
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败，请稍后重试');
    }
}

// 关闭加入班级模态框
export function closeJoinClassModal() {
    //document.getElementById('joinClassModal').style.display = 'none';
    const modal = document.getElementById('joinClassModal');
    modal.classList.remove('active');
    document.body.style.overflow = '';
}

// 确认加入班级
export async function confirmJoinClass() {
    const classCode = document.getElementById('joinClassCode').value.trim();
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    
    if (!classCode) {
        alert('班级编号不能为空');
        return;
    }
    
    try {
        // 获取用户ID
        const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
        const userData = await userResponse.json();
        const userId = userData.user_id;
        
        // 检查班级是否存在
        const checkClassResponse = await fetch(`/check-class-code?classCode=${escapeHTML(classCode)}`);
        const checkClassData = await checkClassResponse.json();
        
        if (!checkClassData.exists) {
            alert('班级不存在');
            return;
        }
        
        // 加入班级
        const joinResponse = await fetch('/join-class', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId,
                classCode
            })
        });
        
        const result = await joinResponse.json();
        alert(result.message);
        
        if (result.success) {
            closeJoinClassModal();
            window.location.href = 'success.html'+window.location.search;
        }
    } catch (error) {
        console.error('加入班级失败:', error);
        alert('加入班级失败，请稍后重试');
    }
}

export async function manageClasses() {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const response = await fetch(`/user-info?username=${escapeHTML(username)}`);
    const data = await response.json();
    
    if (data.role === '教师') {
        window.location.href = `class-manage.html?username=${escapeHTML(username)}`;
    } else {
        alert('该功能为教师专属，非教师无法使用');
    }
}

function escapeHTML(str) {
    return str.replace(/[&<>"']/g, function (match) {
    switch (match) {
    case '&':
    return '&amp;';
    case '<':
    return '&lt;';
    case '>':
    return '&gt;';
    case '"':
    return '&quot;';
    case "'":
    return '&#039;';
}
 });
}